<template>
  <div>
    <el-card shadow="never">
      <el-alert title="添加展览信息" type="info" show-icon:closable="false"></el-alert>
      <el-steps :active="Number(exActiveStep)" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="位置信息"></el-step>
        <el-step title="coser嘉宾"></el-step>
        <el-step title="详情图片"></el-step>
        <el-step title="展览内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-tabs tab-position="left" v-model="exActiveStep" :before-leave="beforeLeave" @tab-change="tabChange">
        <!-- 基本信息 -->
        <el-tab-pane name="0" label="基本信息">
          <el-form :model="exForm" :rules="exFormRules" label-position="top" ref="exFormRef">
            <el-form-item label="展览名称" prop="ex_name">
              <el-input v-model="exForm.ex_name"> </el-input>
            </el-form-item>
            <el-form-item label="主办方" prop="ex_host">
              <el-input v-model="exForm.ex_host"> </el-input>
            </el-form-item>
            <el-form-item label="展览分类" prop="ex_cat">
              <el-cascader v-model="exForm.ex_cat" :options="options" :props="props" :clearable="true"
                placeholder="请选择"></el-cascader>
            </el-form-item>
            <el-form-item label="展览票价" prop="ex_price">
              <el-input v-model="exForm.ex_price" type="number"> </el-input>
            </el-form-item>
            <el-date-picker v-model="exForm.ex_dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form>
        </el-tab-pane>
        <!-- 位置信息 -->
        <el-tab-pane name="1" label="位置信息">
          <input id="inputId">
          <div id="container"></div>
        </el-tab-pane>
        <el-tab-pane name="2" label="coser嘉宾">
          <el-button type="primary" @click="addDialogFormVisible = true">添加嘉宾</el-button>
          <!-- 添加嘉宾对话框 -->
          <el-dialog v-model="addDialogFormVisible" title="添加嘉宾">
            <el-form :model="addForm" :rules="addRules" ref="addRuleFormRef">
              <el-form-item label="coser名称" :label-width="formLabelWidth" prop="nameZzxcsm">
                <el-input v-model="addForm.nameZzxcsm" autocomplete="off" />
              </el-form-item>
              <el-form-item label="coser头像" :label-width="formLabelWidth" prop="imgurlZzxcsm">
                <el-upload class="avatar-uploader" action="http://localhost:9999/zzxcsm/upload" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :on-error="handleAvatarError">
                  <img v-if="addForm.imgurlZzxcsm" :src="addForm.imgurlZzxcsm" class="imgurl" style="width: 100px; height: 100px">
                  <img v-else style="width: 100px; height: 100px"
                    src="https://manz-1318365467.cos.ap-shanghai.myqcloud.com/logo/18c7dafa-495e-4749-b896-36e5b5d330c9.png" />
                </el-upload>
              </el-form-item>
              <el-form-item label="coser简介" :label-width="formLabelWidth" prop="contentZzxcsm">
                <el-input v-model="addForm.contentZzxcsm" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="addSubmitForm(addRuleFormRef)">提交</el-button>
                <el-button @click="addResetForm(addRuleFormRef)">
                  重置
                </el-button>
              </span>
            </template>
          </el-dialog>
          <el-table ref="multipleTableRef" :data="exForm.ex_cosers" style="width: 100%">
            <el-table-column label="名称" width="120">
              <template #default="scope">{{ scope.row.nameZzxcsm }}</template>
            </el-table-column>
            <el-table-column label="头像" width="120">
              <template #default="scope">
                <img :src="scope.row.imgurlZzxcsm" style="width: 50px; height: 50px;" />
              </template>
            </el-table-column>
            <el-table-column property="contentZzxcsm" label="简介" show-overflow-tooltip />
            <el-table-column label="操作" width="90">
              <template #default="scope">
                <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢" :icon="InfoFilled"
                  icon-color="#626AEF" title="你确定要删除这条数据吗?" @onConfirm="deleteCosers(scope.row)"
                  @confirm="deleteCosers(scope.row)">
                  <template #reference>
                    <el-button type="danger" :icon="DeleteOutlined"></el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane name="3" label="详情图片">
          <el-upload action="http://localhost:9999/zzxcsm/upload" :on-preview="handlePreview" :on-remove="handleRemove"
            :file-list="fileList" list-type="picture-card" class="upload-demo" :headers="uploadHeaders"
            :on-success="onSuccess">
            <el-button type="primary">上传展览详情图片</el-button>
            <template #tip>
              <div class="el-upload_tip">
                图片要求：jpg/png文件格式，500kb以内。
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane name="4" label="展览内容">
          <editor api-key="zb75rg0hxvcgq85ox6rkhe4f4l0t2h27tk44ou0kn3dd1a5y" :init="editorInit" v-model="ex_inroduce" />
          <el-button style="margin:20px auto" type="primary" class="add-goods-btn" @click="addEx">添加展览</el-button>
        </el-tab-pane>

      </el-tabs>
    </el-card>
    <el-dialog>
      <el-image :src="dialogImageUrl" alt="dialogImageAlt"></el-image>
    </el-dialog>
  </div>
</template>

<script setup>
import axios from '../../axios.js';
import { ElMessage } from 'element-plus'
import { ref, reactive, onBeforeMount } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import { DeleteOutlined, EditOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { InfoFilled } from '@element-plus/icons-vue'
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
/* 基本信息 */
let exActiveStep = ref('0')
const exForm = reactive({
  ex_id: '',
  ex_name: '',
  ex_host: '',
  ex_cat: 0,
  ex_price: 0,
  ex_dateRange: "",
  ex_sdate: '',
  ex_edate: '',
  ex_city: '',
  ex_address: '',
  ex_cosers: [],
  ex_detail: [],
  ex_content: ''
})
/* 限制规则 */
const exFormRules = reactive({
  ex_name: [
    {
      required: true, message: '请输入展览名称', trigger: 'blur'
    }
  ], ex_host: [
    {
      required: true, message: '请输入举办方', trigger: 'change'
    }
  ], ex_cat: [
    {
      required: true, message: '请输入展览分类', trigger: 'change'
    }
  ], ex_price: [
    {
      required: true, message: '请输入展览票价', trigger: 'blur'
    }, {
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback(); // 校验通过
        } else {
          callback(new Error('票价必须大于0')); // 校验不通过
        }
      }, trigger: 'blur'
    }
  ], ex_dateRange: [
    {
      required: true, message: '请输入展览时间', trigger: 'change'
    }
  ]
})
/* 获取分类列表 */
const getCateList = async () => {
  const { data: res } = await axios.get(`category/list/1`)
  if (res.code !== 1) return
  options.value = res.data
  console.log(options.value);
}
onBeforeMount(() => {
  getCateList()
})
const exFormRef = ref(null)
/* 切换TAP时的一些设置 */
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}
const beforeLeave = (activeName, oldActiveName) => {
  // 当从'基本信息'切出时
  if (oldActiveName === '0') exFormRef.value.validate((valid) => {
    const stimeZzxcsm = formatDate(exForm.ex_dateRange[0])
    const etimeZzxcsm = formatDate(exForm.ex_dateRange[1])
    exForm.ex_sdate = stimeZzxcsm
    exForm.ex_edate = etimeZzxcsm
    if (!valid) {
      exActiveStep.value = '0'
    }
  })
}
const tabChange = (name) => {
  // if (name === '1') return getParams('many')
  // if (name == '2') return getParams('only')
}
/* 选择 */
const options = ref([])
const props = {
  expandTrigger: 'hover',
  value: 'idZzxcsm',
  label: 'styleZzxcsm'
}


/* 位置信息获取 */
import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted, onUnmounted } from "vue";
window._AMapSecurityConfig = {
  securityJsCode: "7d7799daee38cfd8f371a45700c4337c",
}
onMounted(async () => {
  const AMap = await AMapLoader.load({
    key: '04e7465d62ec62a84129ebf8fc14ff23',
    version: '2.0',
    plugins: ["AMap.ToolBar", "AMap.Scale"],
  });
  // 在这里可以使用 AMap 对象进行地图相关的操作
  // 新建地图对象并绑定container
  var map = new AMap.Map("container", {
    resizeEnable: true
  });
  map.setCity('长沙', function () {
    // 设置地图中心点和缩放级别
    map.setZoomAndCenter(10, [112.938813, 28.228209]);
  });
  //输入提示
  var autoOptions = {
    input: "inputId"
  };
  AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
    var auto = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: map
    });  //构造地点查询类
    auto.on("select", select);//注册监听，当选中某条记录时会触发
    function select(e) {
      placeSearch.setCity(e.poi.adcode);
      placeSearch.search(e.poi.name);  //关键字查询查询
      exForm.ex_address = e.poi.district + e.poi.name
      exForm.ex_city = exForm.ex_address.split("市")[0]
      if (exForm.ex_address.indexOf("省")!=-1){
        exForm.ex_city = exForm.ex_address.split("省")[1]
      }
      exForm.ex_city = exForm.ex_city.split("市")[0]
    }
  });
});
/* coser嘉宾 */
import { ElTable } from 'element-plus';
import { forIn, lowerFirst } from 'lodash';
// 添加嘉宾 
const formLabelWidth = '140px';
const addDialogFormVisible = ref(false)
const addForm = reactive({
  nameZzxcsm: '',
  imgurlZzxcsm: '',
  contentZzxcsm: '',
})
// 表单验证
const addRuleFormRef = ref(null)
const addRules = reactive({
  nameZzxcsm: [{
    required: true, message: '请输入coser的名称', trigger: 'blur'
  }],
  imgurlZzxcsm: [{
    required: true, message: '请为coser选择头像', trigger: 'blur'
  }],
  contentZzxcsm: [{
    required: true, message: '请简单介绍一下coser吧', trigger: 'blur'
  }],
})
// 提交表单
const addSubmitForm = (formEL) => {
  addRuleFormRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证成功，执行提交');
      exForm.ex_cosers.push(JSON.parse(JSON.stringify(addForm)))
      formEL.resetFields()
      addDialogFormVisible.value = false
    } else {
      console.log('表单验证失败');
      return false;
    }
  });

}
// 清空表单
const addResetForm = (formEL) => {
  if (!formEL) return
  formEL.resetFields()
}
// 图片上传成功的处理逻辑
const handleAvatarSuccess = (res, file, fileList) => {
  addForm.imgurlZzxcsm = res.data;
  ElMessage.success('头像上传成功');
};
// 图片上传失败的处理逻辑
const handleAvatarError = (err, file, fileList) => {
  ElMessage.error('头像上传失败');
};
const multipleTableRef = ref();
const multipleSelection = ref([]);
// 当选项改变时
const handleSelectionChange = (val) => {
  console.log(val);
  multipleSelection.value = val;
};
// 删除选中的coser
const deleteCosers = (val) => {
  exForm.ex_cosers = exForm.ex_cosers.filter(item => item.nameZzxcsm !== val.nameZzxcsm)
}
/* 详情图片 */
const fileList = ref([
])
// 删除图片
const handleRemove = (uploadFile, uploadFiles) => {
  exForm.ex_detail = exForm.ex_detail.filter(item => item != uploadFile.response.data)
}
const handlePreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true
  dialogImageAlt.value = file.name
}
// 上传图片
const uploadHeaders = {
  Authorization: window.localStorage.getItem('token')
}

const onSuccess = (val) => {
  exForm.ex_detail.push(val.data)
}
/* 漫展内容 */
const editorInit = {
  selector: '#tinymce',//容器，可使用css选择器
  language: 'zh-Hans',
  language_url: '/static/tinymce/langs/zh-Hans.js ',//在public下面
  deprecation_warnings: false,//去掉没用的warning
  height: 300,
  branding: false,//去掉底部水印
  statusbar: false,// 隐藏底部状态栏
  elementpath: false,// 禁用底部状态栏
  menubar: false,//隐藏最上方menu
  plugins: 'table contextmenu image',// 引人插件
  toolbar: 'bold italic underline strikethrough image table / fontsizeselect | alignleft aligncenter alignright alignjustify loutdent indent blockquote / undo redo / removeformat' //菜单配置（一个单词代表了一个功能)
}
const ex_inroduce = ref('')
const dialogImageVisible = ref(false)
const dialogImageUrl = ref('')
const dialogImageAlt = ref('')
const addEx = async () => {
    exForm.ex_content = ex_inroduce.value
    console.log(exForm);
    const { data: res } = await axios.post('ex', {
        categoryIdZzxcsm:exForm.ex_cat[0],
        titleZzxcsm: exForm.ex_name,
        stimeZzxcsm: exForm.ex_sdate,
        etimeZzxcsm: exForm.ex_edate,
        cityZzxcsm: exForm.ex_city,
        addressZzxcsm: exForm.ex_address,
        hostZzxcsm: exForm.ex_host,
        priceZzxcsm: exForm.ex_price,
        detailZzxcsm: exForm.ex_detail.join(","),
        cosersZzxcsm: exForm.ex_cosers,
        contentZzxcsm: exForm.ex_content,
        introduceZzxcsm: ex_inroduce.value
    })
    console.log(res);
    if (res.code !== 1)
        return ElMessage.error(res.meta.msg)
    else
        router.push('/homes/exList')
}
</script>

<style>
#inputId {
  width: 1000px;
  height: 30px;
  margin-top: 10px;
  margin-bottom: 10px;
}

#container {
  width: 1000px;
  height: 400px;
}

.el-alert {
  display: flex;
  justify-content: center;
}

.el-steps {
  margin: 30px 0;
}

.el-input {
  width: 500px;
}

.editor {
  margin: 10px auto;
}
</style>
